package com.project;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class shiroTest {
    public shiroTest() {
//        //创建安全管理器
//        DefaultSecurityManager manager = new DefaultSecurityManager();
//        //设置权限认证的来源，为类路径下的shiro。ini
//        manager.setRealm(new IniRealm("classpath:shiro.ini"));
//        //设置安全管理器
//        SecurityUtils.setSecurityManager(manager);
//
//        //得到主体
//        Subject subject = SecurityUtils.getSubject();
//
//        //产生用户名和密码的令牌
//        UsernamePasswordToken token = new UsernamePasswordToken("tom","123");
//
//        subject.login(token);
//        System.out.println("登录成功");

        DefaultSecurityManager manager = new DefaultSecurityManager();
        manager.setRealm(new CustomerRealm());
        SecurityUtils.setSecurityManager(manager);

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("tom","123");

        try {
            subject.login(token);
            System.out.println("“登录成功");

            //查看当前用户是否具有manager角色
            System.out.println(subject.hasRole("manager"));
            System.out.println(subject.hasAllRoles(List.of("manager","product")));

            //查看当前用户是否拥有指定的权限
            System.out.println(subject.isPermitted("user:create"));
            System.out.println(subject.isPermitted("user:delete"));

            //查看当前用户是否具有指定权限
            System.out.println(subject.isPermittedAll("user:create","order:add"));

        }catch (UnknownAccountException e1){
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e2){
            System.out.println("密码错误");
        }



    }

    public static void main(String[] args) {
        new shiroTest();
    }


}
